// pages/cardbark/inquirysheet/inquirysheet.js
let RM = wx.getRecorderManager();
var address = require("../../../mock.js")
let app = getApp();
let testAddr = app.globalData.testAddr;
Page({
 /**
    * 控件当前显示的数据
    * provinces:所有省份
    * citys 选择省对应的所有市,
    * areas 选择市对应的所有区
    * areaInfo：点击确定时选择的省市县结果
    * animationAddressMenu：动画
    * addressMenuIsShow：是否可见
    */
  /**
   * 页面的初始数据
   */
  data: {
    dates: '',
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0, 0],
    provinces: [],
    citys: [],
    areas: [],
    areaInfo: '',
    typeOneLevel: [],
    typeTwoLevel: [],
    typeThreeLevel: [],
    oneLevelClickStyleNode: {one1:"1"},
    oneLevelHaveClickStyle:{},
    twoLevelClickStyleNode: { two1: "1"},
    twoLevelHaveClickStyle:{},
    threeLevelClickStyleNodes: {},
    oneLevelClickNodes: [],
    twoLevelClickNodes: [],
    threeLevelClickNodes: [],
    currentOneLevelId:"1",
    currentTwoLevelId:"1",
    typeParams:{},
    recordStatus:"",
    isRecord:false,
    recordTipsShow:false,
    videoPlayShow:false,

    description:"",//描述
    reason:"",//询价理由
    guestID:"",//用户ID
    projectName:"",//产品名称
    openBill:"",//发票：1 是 2 否
    transportation:"",//运输费 1 是 2否
    productTypeID:"",//二级产品类型
    menuId:"",//一级产品类型
    address:"",//交货地址
    submitTime:"",//交货时间
    saveValidate:"",//1 保存 2 提交
    playAddress:"",//音频文件,
    enquiryInfos:[],//图片集合
    addressInfo:{},//地址对象
    enquiryProductList:[]//询价产品集合
  },
    

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 默认联动显示北京
    var id = address.provinces[0].id
    this.setData({
      provinces: address.provinces,
      citys: address.citys[id],
      areas: address.areas[address.citys[id][0].id],
    })
  },
  //  点击日期组件确定事件  
  bindDateChange: function (e) {
  
    this.setData({
      dates: e.detail.value,
    })
  },

  // 点击所在地区弹出选择框
  select: function (e) {
    // 如果已经显示，不在执行显示动画
    if (this.data.addressMenuIsShow) {
      return false
    } else {
      // 执行显示动画
      this.startAddressAnimation(true)
    }
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      this.animation.translateY(0 + 'vh').step()
    } else {
      this.animation.translateY(40 + 'vh').step()
    }
    this.setData({
      animationAddressMenu: this.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  typesSelectShow(){
    this.setData({
      addressMenuIsShow:true
    });
  },
  typesSelectHide(){
    this.setData({
      addressMenuIsShow: false
    });
  },
  // 点击地区选择取消按钮
  cityCancel: function (e) {
    this.startAddressAnimation(false)
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    var that = this
    var city = that.data.city
    var value = that.data.value
    this.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    var areaInfo = that.data.provinces[value[0]].name + '-' + that.data.citys[value[1]].name + '-' + that.data.areas[value[2]].name
    that.setData({
      areaInfo: areaInfo,
    })
  },
  // 处理省市县联动逻辑
  cityChange: function (e) {
    var value = e.detail.value
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var provinceNum = value[0]
    var cityNum = value[1]
    var countyNum = value[2]
    // 如果省份选择项和之前不一样，表示滑动了省份，此时市默认是省的第一组数据，
    if (this.data.value[0] != provinceNum) {
      var id = provinces[provinceNum].id
      this.setData({
        value: [provinceNum, 0, 0],
        citys: address.citys[id],
        areas: address.areas[address.citys[id][0].id],
      })
    } else if (this.data.value[1] != cityNum) {
      // 滑动选择了第二项数据，即市，此时区显示省市对应的第一组数据
      var id = citys[cityNum].id
      this.setData({
        value: [provinceNum, cityNum, 0],
        areas: address.areas[citys[cityNum].id],
      })
    } else {
      // 滑动选择了区
      this.setData({
        value: [provinceNum, cityNum, countyNum]
      })
    }
  },
  //三级多选联动
  oneLevelClick:function(e){
    let index = 'one' + e.target.id;
    let that=this;
    let clickNodes={};
    clickNodes[index]="1";
    this.setData({
      oneLevelClickStyleNode: clickNodes,
      currentOneLevelId: e.target.id
    });
    this.getTwoLevelTypes();
    this.getThreeLevelTypes();
  },
  twoLevelClick: function (e) {
    let index = 'two' + e.target.id;
    let that = this;
    let clickNodes = {};
    clickNodes[index] = "1";
    this.setData({
      twoLevelClickStyleNode: clickNodes,
      currentTwoLevelId: e.target.id
    });
    this.getThreeLevelTypes();
  },

  threeLevelClick:function(e) {
    let that=this;
    let index="three"+e.target.id;
    let threeLevelClickNodes=[];
    for (let i in that.data.threeLevelClickNodes){
      let code = that.data.threeLevelClickNodes[i];
      threeLevelClickNodes.push(code);
    }
    let threeLevelClickStyleNodes={};
    for (let i in that.data.threeLevelClickStyleNodes){
      threeLevelClickStyleNodes[i] = that.data.threeLevelClickStyleNodes[i];
    }
    let j=0;
    let flag=true;
    for (let i in threeLevelClickNodes){
      if (threeLevelClickNodes[i] == e.target.id){
        j=i;
        flag=false;
        break;
      }
    }
    let typeThreeLevel = that.data.typeThreeLevel;
    let oneLevelHaveClickStyle={};
    for (let i in that.data.oneLevelHaveClickStyle){
      oneLevelHaveClickStyle[i] = that.data.oneLevelHaveClickStyle[i];
    }
    let twoLevelHaveClickStyle = {};
    for (let i in that.data.twoLevelHaveClickStyle) {
      twoLevelHaveClickStyle[i] = that.data.twoLevelHaveClickStyle[i];
    }
    
    let twoLevelClickNodes = [];
    let twoCode = that.data.currentTwoLevelId;
    let twoIsHave=false;
    for (let i in that.data.twoLevelClickNodes) {
      twoLevelClickNodes.push(that.data.twoLevelClickNodes[i]);
      if (that.data.twoLevelClickNodes[i] == twoCode){
        twoIsHave=true;
      }
    }
    let topParent=that.data.currentOneLevelId;
    let oneIsHave = false;
    let oneLevelClickNodes = [];
    for (let i in that.data.oneLevelClickNodes) {
      oneLevelClickNodes.push(that.data.oneLevelClickNodes[i]);
      if (topParent == that.data.oneLevelClickNodes[i]){
        oneIsHave=true;
      }
    }
    let typeParams = {};
    for (let i in that.data.typeParams){
      typeParams[i]=that.data.typeParams[i];
    }
    if(flag){
      if (!oneIsHave){
        oneLevelClickNodes.push(topParent);
        oneLevelHaveClickStyle["have"+topParent]="1";
      }
      typeParams['typerow'+e.target.id]={
        menuid: e.currentTarget.dataset.menuid,
        producttypeid: e.currentTarget.dataset.producttypeid,
        productThirdId: e.currentTarget.dataset.productthirdid,
      };
      
      if(!twoIsHave){
        twoLevelClickNodes.push(twoCode);
        twoLevelHaveClickStyle["have" + twoCode+"have"+topParent] = "1";
      }
      threeLevelClickNodes.push(e.target.id);
      threeLevelClickStyleNodes[index]="1";
      if (e.target.id == 'all'){
        threeLevelClickNodes=[];
        threeLevelClickStyleNodes={};
        for (let i in typeThreeLevel){
          let id = typeThreeLevel[i].code;
          let menuid = typeThreeLevel[i].menuid;
          let producttypeid = typeThreeLevel[i].producttypeid;
          threeLevelClickNodes.push(id);
          threeLevelClickStyleNodes["three" + id]="1";
          typeParams['typerow' + id]={
            menuid: menuid,
            producttypeid: producttypeid,
            productthirdid:id
          }
        }
      }
    }else{
      typeParams['typerow' + e.target.id]=undefined;
      threeLevelClickNodes.splice(j,1);
      threeLevelClickStyleNodes[index] = undefined;
      for (let i in threeLevelClickNodes){
        if (threeLevelClickNodes[i] == 'all'){
          threeLevelClickNodes.splice(i, 1);
          threeLevelClickStyleNodes["threeall"]=undefined;
          break;
        }
      }
      
      if (e.target.id == 'all'){
        threeLevelClickNodes=[];
        threeLevelClickStyleNodes={};
        for (let i in typeThreeLevel){
          let id = typeThreeLevel[i].code;
          typeParams['typerow' + id] = undefined;
        }
      }
      if (threeLevelClickNodes.length == 0) {
        for (let i in twoLevelClickNodes) {
          if (twoCode == twoLevelClickNodes[i]) {
            twoLevelClickNodes.splice(i, 1);
            twoLevelHaveClickStyle["have" + twoCode + "have" + topParent] = undefined;
          }
        }
      }
      if (twoLevelClickNodes.length == 0) {
        for (let i in oneLevelClickNodes) {
          if (topParent == oneLevelClickNodes[i]) {
            oneLevelClickNodes.splice(i, 1);
            oneLevelHaveClickStyle["have" + topParent] = undefined;
          }
        }
      }
      
    }
    console.log(JSON.stringify(typeParams));
    that.setData({
      threeLevelClickNodes: threeLevelClickNodes,
      threeLevelClickStyleNodes: threeLevelClickStyleNodes,
      twoLevelClickNodes: twoLevelClickNodes,
      twoLevelHaveClickStyle: twoLevelHaveClickStyle,
      oneLevelClickNodes: oneLevelClickNodes,
      oneLevelHaveClickStyle: oneLevelHaveClickStyle,
      typeParams: typeParams
    });
  },
  //获取一级分类
  getOneLevelTypes:function(){
    let that=this;
    let typeOneLevel=[];
    app.util.request({
      url: testAddr + "menuItem/menu",
      method: "POST",
      data: {

      },
      success: function (res) {
        let data = res.data;
        for(let i in data){
          typeOneLevel.push({ code: data[i].ID, name: data[i].menuName});
        }
        that.setData({
          typeOneLevel: typeOneLevel
        });
      },
      fail: function (res) {

      },
      complete: function (res) {

      },
    });
  },
  //获取二级分类
  getTwoLevelTypes: function () {
    let that = this;
    let typeTwoLevel = [];
    app.util.request({
      url: testAddr + "ProductType/getAllType?menuID=" + that.data.currentOneLevelId,
      method: "POST",
      data: {
      },
      success: function (res) {
        let data = res.data;
        for (let i in data) {
          typeTwoLevel.push({ code: data[i].ID, name: data[i].typeName,parent:that.data.currentOneLevelId });
        }
        that.setData({
          typeTwoLevel: typeTwoLevel
        });
      },
      fail: function (res) {

      },
      complete: function (res) {

      },
    });
  },
  //获取三级分类
  getThreeLevelTypes: function () {
    let that = this;
    let typeThreeLevel = [];
    let threeLevelClickStyleNodes = that.data.threeLevelClickStyleNodes;
    
    for (let i in that.data.threeLevelClickStyleNodes){
      threeLevelClickStyleNodes[i] = that.data.threeLevelClickStyleNodes[i];
    }
    app.util.request({
      url: testAddr + "ProductType/getProductById?typeid=" + that.data.currentOneLevelId + "&productTypeId=" + that.data.currentTwoLevelId,
      method: "POST",
      data: {
      },
      success: function (res) {
        let data = res.data;
        console.log(threeLevelClickStyleNodes);
        typeThreeLevel.push({code:"all",name:"全部"});
        threeLevelClickStyleNodes["threeall"]=undefined;
        for (let i in data) {
        typeThreeLevel.push({ code: data[i].id, name: data[i].productname, parent: data[i].producttypeid, menuid: data[i].typeid, producttypeid: data[i].producttypeid, productThirdId:data[i].id});
        }
        that.setData({
          typeThreeLevel: typeThreeLevel,
          threeLevelClickStyleNodes: threeLevelClickStyleNodes
        });
      },
      fail: function (res) {

      },
      complete: function (res) {

      },
    });
  },
  startUpRecording(e){
    var that = this;
    
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success() {
              
            }
          })
        }
      }
    })
    
  },
  startRecord(e){
    let that=this;
    if (that.data.isRecord == true) {
      that.setData({
        recordTipsShow: true
      });
      return;
    }
    var startTime = e.timeStamp;
    that.setData({
      startTime: startTime
    })
    wx.showLoading({
      title: '开始录音',
      mask: true
    })
    let recorderManager = wx.getRecorderManager();
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    const options = {
      duration: 10000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 96000,
      format: 'mp3',
      frameSize: 50
    }
    recorderManager.start(options);
  },
  endRecord(e){
    var endTime = e.timeStamp;
    let that=this;
    wx.hideLoading();
    let recorderManager = wx.getRecorderManager();
    recorderManager.stop();
    recorderManager.onStop((res)=>{
      var tempFilePath = res.tempFilePath;
      wx.uploadFile({
        url: 'https://www.goods-asked.cn/hwsjEmp/enquiry/uploadAudio',
        filePath: tempFilePath,
        name: 'file',
        header: {
          contentType: "multipart/form-data",//按需求增加
        },
        success: function (res) {
          console.log(res);
          that.setData({
            playAddress:res.data,
            isRecord:true
          });
          wx.showToast({
            title: "录制成功",
          })
        }
      })
      
    })
  },
  hideTips(){
    this.setData({
      recordTipsShow:false
    });
  },
  audioPlay: function () {
    this.setData({
      recordTipsShow: false
    });
    this.audioCtx.play();
  },
  audioPause: function () {
    this.audioCtx.pause()
    this.setData({
      recordTipsShow: false
    });
  },
  audioStart: function () {
    this.audioCtx.seek(0)
  },
  videoPlayShow(){
    this.setData({
      videoPlayShow:true,
      recordTipsShow: false
    });
  },
  restartRecord(){
    this.setData({
      isRecord: true,
      recordTipsShow: false
    });
  },
  quitPlay(){
    this.setData({
      videoPlayShow: false,
      recordTipsShow: false
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getOneLevelTypes();
    this.getTwoLevelTypes();
    this.getThreeLevelTypes();
    this.audioCtx = wx.createAudioContext('myAudio');
  },

  /**
   * 生命周期函数--监听页面显示
   */
    onShow: function () {
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'linear',
      })
      this.animation = animation
    },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})